<?php


namespace app\madmin\service;


use app\madmin\model\Configuration;
use app\madmin\model\SignIn;
use think\Exception;

class SignInService
{
    /**
     * @param string $config
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(array $config) : array{
        global $user;
//        if (!empty($config['continuity'])){
//            foreach ($config['continuity'] AS $key => $value){
//                if ($value['pattern'] == 'month' && $value['day'] > 28)
//                    throw new Exception('按月计算连续签到情况下天数不得超过28天',HTTP_INVALID);
//            }
//        }
        $model = new Configuration();
        $model = $model
            ->where('mall_id',$user['mall_id'])
            ->where('type','signIn')
            ->find();
        $model->save(['configuration' => $config]);
        return [HTTP_SUCCESS,$model->where('type','signIn')->find()];
    }

    /**
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function list(int $page, int $size, array $data){
        $Sign = new SignIn();
        $where = $this->where($data);
        if(!empty($where))
            $Sign = $Sign->where('user_id','IN',function($sql) use ($where){
                $sql->name('user')->field('id')->where($where);
            });
        $list = $Sign
            ->with(['UserNicknamePicurl'])
            ->order('create_time DESC')
            ->paginate(['page' => $page,'list_rows' => $size]);
        return [HTTP_SUCCESS,$list];
    }

    /**
     * @param array $data
     * @return array
     */
    public function where(array $data) : array{
        $where = [];
        !empty($data['nickname']) && $where[] = ['nickname','like',$data['nickname'].'%'];
        !empty($data['mobile']) && $where[] = ['mobile','like',$data['mobile'].'%'];
        return $where;
    }

}